package appcus

import (
	"counter-help/admin/server/global"
	appReq "counter-help/admin/server/model/app/response"
	"counter-help/admin/server/model/customer"
	"errors"
	"fmt"
	"math"
	"time"
)

// AppDataService 后台数据中心
type AppDataService struct{}

// RequireIncreaseService 新增需求的数量
func (s *AppDataService) RequireIncreaseService() (resp appReq.AppRequireIncreaseResponse, err error) {
	var todayCount, totalCount int64

	// 获取当天的开始和结束时间
	todayStart := time.Now().Truncate(24 * time.Hour)
	tomorrowStart := todayStart.Add(24 * time.Hour)

	// 获取 当天新增数据
	err = global.GVA_DB.
		Model(&customer.CusOrder{}).
		Where("created_at >= ? AND created_at < ?", todayStart, tomorrowStart).
		Where("deleted_at IS NULL").
		Where("status = ?", 1).
		Count(&todayCount).Error
	if err != nil {
		return resp, errors.New("获取新增数据失败")
	}

	// 新增数据站百分比
	err = global.GVA_DB.Model(&customer.CusOrder{}).Where("deleted_at IS NULL").Count(&totalCount).Error
	if err != nil {
		return resp, errors.New("获取数据总量失败")
	}

	percentage := float64(0)
	if totalCount > 0 {
		// 计算百分比并保留两位小数
		percentage = math.Round((float64(todayCount)/float64(totalCount)*100)*100) / 100
	}

	// 前一周内新增数量
	data, err := getDailyCountsForLastWeek(1)
	if err != nil {
		return resp, errors.New("获取一周数据失败")
	}

	// 返回结果
	resp.Value = todayCount
	resp.Percentage = percentage
	resp.Data = data

	return
}

// OrderIncreaseService 新增订单的数量
func (s *AppDataService) OrderIncreaseService() (resp appReq.AppOrderIncreaseResponse, err error) {
	var todayCount, totalCount int64

	// 获取当天的开始和结束时间
	todayStart := time.Now().Truncate(24 * time.Hour)
	tomorrowStart := todayStart.Add(24 * time.Hour)

	// 获取 当天新增数据
	err = global.GVA_DB.
		Model(&customer.CusOrder{}).
		Where("created_at >= ? AND created_at < ?", todayStart, tomorrowStart).
		Where("deleted_at IS NULL").
		Where("status = ?", 3).
		Count(&todayCount).Error
	if err != nil {
		return resp, errors.New("获取新增订单数据失败")
	}

	// 新增数据站百分比
	err = global.GVA_DB.Model(&customer.CusOrder{}).Where("deleted_at IS NULL").Count(&totalCount).Error
	if err != nil {
		return resp, errors.New("获取数据总量失败")
	}

	percentage := float64(0)
	if totalCount > 0 {
		// 计算百分比并保留两位小数
		percentage = math.Round((float64(todayCount)/float64(totalCount)*100)*100) / 100
	}

	// 前一周内新增数量
	data, err := getDailyCountsForLastWeek(3)
	if err != nil {
		return resp, errors.New("获取一周数据失败")
	}

	// 返回结果
	resp.Value = todayCount
	resp.Percentage = percentage
	resp.Data = data

	return
}

// UserIncreaseService 新增用户的数量
func (s *AppDataService) UserIncreaseService() (resp appReq.AppUserIncreaseResponse, err error) {
	var todayCount, totalCount int64

	// 获取当天的开始和结束时间
	todayStart := time.Now().Truncate(24 * time.Hour)
	tomorrowStart := todayStart.Add(24 * time.Hour)

	// 获取 当天新增数据
	err = global.GVA_DB.
		Model(&customer.CusUser{}).
		Where("created_at >= ? AND created_at < ?", todayStart, tomorrowStart).
		Where("deleted_at IS NULL").
		Count(&todayCount).Error
	if err != nil {
		return resp, errors.New("获取新增用户数据失败")
	}

	// 新增数据站百分比
	err = global.GVA_DB.Model(&customer.CusUser{}).Where("deleted_at IS NULL").Count(&totalCount).Error
	if err != nil {
		return resp, errors.New("获取用户数据总量失败")
	}

	percentage := float64(0)
	if totalCount > 0 {
		// 计算百分比并保留两位小数
		percentage = math.Round((float64(todayCount)/float64(totalCount)*100)*100) / 100
	}

	// 前一周内新增数量
	data, err := getDailyUserCountsForLastWeek()
	if err != nil {
		return resp, errors.New("获取一周数据失败")
	}

	// 返回结果
	resp.Value = todayCount
	resp.Percentage = percentage
	resp.Data = data

	return
}

// 获取上周订单表增加数据
func getDailyCountsForLastWeek(status int) ([]int64, error) {
	var results []int64
	// 获取今天的日期
	today := time.Now().Truncate(24 * time.Hour)

	// 遍历过去7天的日期
	for i := 0; i < 7; i++ {
		dayStart := today.AddDate(0, 0, -i)
		dayEnd := dayStart.Add(24 * time.Hour)

		var count int64
		err := global.GVA_DB.Model(&customer.CusOrder{}).
			Where("created_at >= ? AND created_at < ?", dayStart, dayEnd).
			Where("deleted_at IS NULL").
			Where("status = ?", status).
			Count(&count).Error

		if err != nil {
			global.GVA_LOG.Error(fmt.Sprintf("获取 %s 的数据失败: %s", dayStart.Format("2006-01-02"), err))
			return nil, err
		}

		results = append(results, count)
	}

	// 结果数组从最近日期到较早日期
	return results, nil
}

// 获取上周用户表增加数据
func getDailyUserCountsForLastWeek() ([]int64, error) {
	var results []int64
	// 获取今天的日期
	today := time.Now().Truncate(24 * time.Hour)

	// 遍历过去7天的日期
	for i := 0; i < 7; i++ {
		dayStart := today.AddDate(0, 0, -i)
		dayEnd := dayStart.Add(24 * time.Hour)

		var count int64
		err := global.GVA_DB.Model(&customer.CusUser{}).
			Where("created_at >= ? AND created_at < ?", dayStart, dayEnd).
			Where("deleted_at IS NULL").
			Count(&count).Error

		if err != nil {
			global.GVA_LOG.Error(fmt.Sprintf("获取 %s 的数据失败: %s", dayStart.Format("2006-01-02"), err))
			return nil, err
		}

		results = append(results, count)
	}

	// 结果数组从最近日期到较早日期
	return results, nil
}
func (a *AppDataService) GetOrderCountLast7Weeks() ([]appReq.AppOrderWeeklyCountResponse, error) {
	var results []appReq.AppOrderWeeklyCountResponse

	// 使用 GORM 构建查询，获取最近7周的数据
	err := global.GVA_DB.
		Model(&customer.CusOrder{}).
		Select("DATE_FORMAT(created_at, '%Y-%u') AS week, COUNT(*) AS count").
		Where("created_at >= DATE_SUB(CURDATE(), INTERVAL 7 WEEK)").
		Where("deleted_at IS NULL").
		Group("week").
		Order("week DESC").
		Scan(&results).Error

	if err != nil {
		return nil, err
	}

	return results, nil
}
